﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using RuiXinCoffee.Utils;
using System.Data;

namespace RuiXinCoffee.DAL
{
    internal class BaseDAO<T> where T : class, new()
    {
        // 通用添加方法
        protected int Insert(string sql, params MySqlParameter[] parameters)
        {
            try
            {
                return DBhelp.ExecuteNonQuery(sql, parameters);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("数据插入失败：" + ex.Message);
            }
        }

        // 通用更新方法
        protected int Update(string sql, params MySqlParameter[] parameters)
        {
            try
            {
                return DBhelp.ExecuteNonQuery(sql, parameters);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("数据更新失败：" + ex.Message);
            }
        }

        // 通用删除方法
        protected int Delete(string sql, params MySqlParameter[] parameters)
        {
            try
            {
                return DBhelp.ExecuteNonQuery(sql, parameters);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("数据删除失败：" + ex.Message);
            }
        }

        // 通用查询方法，返回数据表
        protected DataTable Select(string sql, params MySqlParameter[] parameters)
        {
            try
            {
                return DBhelp.ExecuteDataTable(sql, parameters);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("数据查询失败：" + ex.Message);
            }
        }

        // 通用查询方法，返回对象列表
        protected List<T> SelectList(string sql, params MySqlParameter[] parameters)
        {
            try
            {
                return DBhelp.ExecuteScalarList<T>(sql, parameters);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("数据查询失败：" + ex.Message);
            }
        }

        // 通用查询方法，返回单个对象
        protected T SelectSingle(string sql, params MySqlParameter[] parameters)
        {
            try
            {
                List<T> list = DBhelp.ExecuteScalarList<T>(sql, parameters);
                return list.Count > 0 ? list[0] : null;
            }
            catch (Exception ex)
            {
                throw new ApplicationException("数据查询失败：" + ex.Message);
            }
        }
    }
}
